export default {
	props: {
		value: { type: Boolean, default: false },
		dataId: { type: String, default: '' },
		isSub: { type: Boolean, default: false },
		disable: { type: Boolean, default: false }
	},
	data() {
		return {
			visible: this.value,
			formData: {},
			loading: false,
			btnLoading: false
		}
	},
	computed: {
		addOrEdit() {
			return !this.dataId;
		},
		formType() {
			if (this.addOrEdit) {
				return 'add';
			} else if (this.isSub) {
				return 'addSub';
			} else if (this.disable) {
				return 'detail';
			} else {
				return 'edit';
			}
		},
		formTypeText() {
			if (this.formType === 'edit') {
				return '编辑';
			} else if (this.formType === 'detail') {
				return '查看';
			} else {
				return '新增';
			}
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		async visible(flag) {
			this.$emit('input', flag);
			if (!flag) {
				this.isSub = false;
				this.$nextTick(() => {
					this.$refs['form']?.resetFields();
					this.formData = {};
				})
			} else {
				await this.initializeFormData();
				if (!!this.formatFormParams) {
					this.formatFormParams();
				}
			}
		}
	},
	methods: {
		//获取详情参数
		formatDetailParams() {
			if (!this.requestParams) {
				return this.dataId;
			} else {
				return this.requestParams;
			}
		},

		//初始化表单数据
		async initializeFormData() {
			this.loading = true;
			if (this.formType === 'addSub') {
				this.formData = { pid: this.dataId };
			} else if (['edit', 'detail'].some(n => n === this.formType)) {
				let params = this.formatDetailParams();
				let result = await this.detailData(params).then((res) => res.data);
				if (result.code === '0') {
					this.formData = this.$detailData(result.data);
				}
			}
			this.loading = false;
		},

		//提交表单
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				if (!!this.verifyChildForm) {
					let valid = await this.verifyChildForm();
					!!valid && await this.submitFormRequest();
				} else {
					await this.submitFormRequest();
				}
				this.btnLoading = false;
			});
		},

		//格式化请求参数
		async formatRequestParams() {
			if (!this.submitParams) {
				return Promise.resolve(this.formData);
			} else {
				return Promise.resolve(this.submitParams);
			}
		},

		//提交表单请求
		async submitFormRequest() {
			let params = await this.formatRequestParams();
			let tipTxt = `${this.formTypeText}${this.formName}`;
			let result = await this.callFunction(params).then(res => res.data);
			if (result.code === '0') {
				this.visible = false;
				this.$emit('refresh', params.pid);
				this.$message.success(`${tipTxt}成功`);
				if (!!this.updateStoreData) {
					this.updateStoreData();
				}
			}
		}
	}
}